﻿using CarouselView.Contracts;
using CarouselView.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace CarouselView.ViewModels
{
    public class MainViewModel: NotifyPropertyBase
    {
        public MainViewModel(IDirectoryContract directoryContract,IDownloadContract downloadContract)
        {
            Images = new ObservableCollection<string>()
            {
                "https://seopic.699pic.com/photo/50110/8335.jpg_wh1200.jpg",
                "https://pic4.zhimg.com/v2-87d78fc44236a144aa52cd8ea18e9da2_r.jpg",
                "https://img.zcool.cn/community/0196e45ae35302a80120927bda8804.jpg@2o.jpg",
                "https://clubimg.club.vmall.com/data/attachment/forum/202006/03/210216pnzsu3qfkaq09pv2.jpg"
            };

            DownloadCommand = new Command(
                execute: async () =>
                {
                    if (Images.Count == 0 || Position < 0 || Position >= Images.Count)
                    {
                        return;
                    }

                    try
                    {
                        string fileName = Images[Position];
                        string docsDirectory = directoryContract.GetPictureDirectory();
                        string path = $"{docsDirectory}/{Path.GetFileName(fileName)}";

                        await downloadContract.Download(fileName, path);
                        await Shell.Current.DisplayAlert("图片保存路径", path, "关闭");
                    }
                    catch (Exception e)
                    {
                        await Shell.Current.DisplayAlert("错误", e.Message, "关闭");
                    }
                },
                canExecute: () => true
            );
        }

        /// <summary>
        /// 图片加载框
        /// </summary>
        public ObservableCollection<string> Images { set; get; }
        private int _position;
        public int Position
        {
            set
            {
                _position = value;
                RaiseChange("Position");
            }
            get
            {
                return _position;
            }
        }

        /// <summary>
        /// 下载命令
        /// </summary>
        public ICommand DownloadCommand { set; get; }

    }
}
